<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <ShedulingAdjustmentTree
      class="w-1/4 xl:w-1/5 treeList"
      @select="handleSelect"
      @ok="onClose"
      ref="treeRef"
    />
    <div class="mt-4 mb-4 ml-1 w-3/4 xl:w-4/5 bg-white">
      <div class="flex justify-center items-center">
        <DatePicker v-model:value="yearMonth" picker="month" @change="handleChangeMonth" />
        <Select
          placeholder="请选择"
          v-model:value="selectedValue"
          style="margin: 10px; width: 150px"
          :allow-clear="false"
        >
          <SelectOption v-for="item in schedulingList" :key="item.id" :value="item.id">
            <div
              :style="{ backgroundColor: item.color ? item.color : '#fff', textAlign: 'center' }"
            >
              {{ item.name }}
            </div>
          </SelectOption>
        </Select>
        <a-button type="primary" @click="handleSave" :loading="isSave">保存</a-button>
      </div>
      <BasicTable @register="registerTable">
        <template #headerCell="{ title, column }">
          <div
            :class="{
              'bg-yellow-200':
                days &&
                days.length &&
                days.filter((item) => item.day == column.dataIndex)[0]?.isWorkDay == false,
            }"
            >{{ column.customTitle || title }}</div
          >
        </template>
        <template #footer>
          <div class="text-center pt-2 pb-2">
            (点击或拖动鼠标可以排班，o 表示是已被调整的排班，* 表示正被调整还没有保存)
          </div>
        </template>
      </BasicTable>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, unref, nextTick } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { Select, DatePicker } from 'ant-design-vue';
  import ShedulingAdjustmentTree from './/modules/ShedulingAdjustmentTree.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { BasicTable, useTable } from '/@/components/Table';
  import type { Dayjs } from 'dayjs';
  import { dateUtil as dayjs } from '/@/utils/dateUtil';
  import { getSelectRow, getColumns } from './schedulingAdjustment.data';
  import {
    getAttendanceListShift,
    getAttendanceListForAdjust,
    getAttendanceSaveShiftAdjust,
  } from '/@/api/module/module';
  import { isArray } from '/@/utils/is';
  import { useI18n } from '/@/hooks/web/useI18n';

  export default defineComponent({
    name: 'ShedulingAdjustment',
    components: {
      PageWrapper,
      ShedulingAdjustmentTree,
      Select,
      BasicTable,
      DatePicker,
      SelectOption: Select.Option,
    },
    setup() {
      const { createMessage } = useMessage();
      const treeRef: any = ref(null);
      let dataRef = ref<Recordable>({});
      const userStore = useUserStore();
      const yearMonth = ref<Dayjs | String | undefined>();
      const deptCode = ref('');
      const days = ref([]); //取第一条的记录，识别休息日
      const { t } = useI18n();
      const fetch = async () => {
        if (!unref(deptCode)) {
          return createMessage.warning('请选择部门');
        }
        if (!unref(yearMonth)) {
          return createMessage.warning('请选择月份');
        }
        const params = {
          deptCode: unref(deptCode),
          showYear: dayjs(unref(yearMonth)).format('YYYY'),
          showMonth: dayjs(unref(yearMonth)).format('MM'),
        };
        await setProps({ searchInfo: params });
        await reload();
        await redoHeight();
      };
      onMounted(async () => {
        await nextTick();
        yearMonth.value = dayjs();
        setCurrentColumns();
        getAttendanceListShiftData();
      });
      const getSelectedValue = () => {
        const record = schedulingList.value.find((item) => item.id == selectedValue.value);
        return record;
      };
      const setCurrentColumns = () => {
        const columns = getColumns(yearMonth.value, getSelectedValue);
        setColumns(columns);
      };
      // let selectRow = ref<Recordable[]>([]);
      // const isClick = ref(false);
      const [
        registerTable,
        { reload, setProps, setTableData, setColumns, redoHeight, getDataSource },
      ] = useTable({
        title: '',
        api: getAttendanceListForAdjust,
        columns: [],
        formConfig: {
          labelWidth: 120,
        },
        searchInfo: {}, //额外的参数
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        immediate: false,
        afterFetch: (data) => {
          if (isArray(data)) {
            days.value = data[0].days;
            data.forEach((item) => {
              item.days.forEach((el) => {
                el.newShiftId = el.shiftId;
              });
            });
          }
          return data;
        },
        // beforeFetch: (info) => {
        //   let newInfo = info;
        //   return newInfo;
        // },
        // actionColumn: {
        //   width: 120,
        //   title: '操作',
        //   dataIndex: 'action',
        //   slots: { customRender: 'action' },
        //   fixed: 'right',
        // },
      });

      function handleSelect(val = '', node) {
        console.log({ val, node });
        deptCode.value = val;
        dataRef.value = {};
        if (val) {
          dataRef.value = node;
          fetch();
        } else {
          onClose();
        }
      }

      let serverInfo = userStore.getServerInfo;
      console.log('serverInfo', serverInfo);

      function onClose(e?: number) {
        if (e != 1) {
          //1是新增，不用清空
          dataRef.value = {};
        }
      }

      //排班列表
      const schedulingList = ref<Recordable[]>([]);
      const selectedValue = ref('');
      //获取排班列表
      const getAttendanceListShiftData = async () => {
        const data = await getAttendanceListShift();
        schedulingList.value = data || [];
        if (isArray(unref(schedulingList)) && unref(schedulingList).length) {
          schedulingList.value.unshift({
            name: '无班次',
            id: -5,
            color: '#fff',
          });
          selectedValue.value = unref(schedulingList)[1]?.id;
        }
      };

      const handleChangeMonth = async () => {
        await setCurrentColumns();
        await fetch();
      };

      const isSave = ref(false);
      //save
      const handleSave = async () => {
        console.log(getSelectRow());
        const data = await getDataSource();
        console.log('data', data);
        if (data.length == 0) return;
        let selectedData: any = [];
        data.forEach((item) => {
          if (isArray(item.days)) {
            item.days.forEach((el) => {
              if (el.operate == 0) {
                selectedData.push({
                  shiftId: el.shiftId,
                  shiftName: el.shiftName,
                  userName: item.userName,
                  date: `${dayjs(unref(yearMonth)).format('YYYY-MM')}-${
                    el.day < 10 ? '0' + el.day : el.day
                  }`,
                  operate: 0, // 0是清除
                });
              } else if (el.operate == 1) {
                selectedData.push({
                  shiftId: el.shiftId,
                  shiftName: el.shiftName,
                  userName: item.userName,
                  date: `${dayjs(unref(yearMonth)).format('YYYY-MM')}-${
                    el.day < 10 ? '0' + el.day : el.day
                  }`,
                  operate: 1, // 1是新增调整，带*号的
                });
              }
            });
          }
        });
        console.log('selectedData', selectedData);
        // 提交
        await getAttendanceSaveShiftAdjust({ data: JSON.stringify(selectedData) }).then(() => {
          createMessage.success(t('common.opSuccess'));
          reload();
        });

        isSave.value = true;
        setProps({ loading: true });
        setTimeout(() => {
          isSave.value = false;
          setProps({ loading: false });
        }, 2000);
      };
      return {
        handleSelect,
        treeRef,
        dataRef,
        onClose,
        registerTable,
        yearMonth,
        schedulingList,
        handleChangeMonth,
        handleSave,
        selectedValue,
        isSave,
        days,
      };
    },
  });
</script>
<style lang="less" scoped>
  :deep(.ant-table-body) {
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* Internet Explorer/Edge */
    user-select: none;
  }
  :deep(.ant-picker-input input) {
    text-align: center;
  }
</style>
